package com.bishe.demo.modules.other.dao;

import com.bishe.demo.modules.account.entity.User;
import com.bishe.demo.modules.common.entity.SearchBean;
import com.bishe.demo.modules.other.entity.Travel;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface TravelDao {
    @Insert("insert into other_travel values(null,#{travelName},#{travelDetail},#{createTime})")
    @Options(useGeneratedKeys = true, keyProperty = "travelId", keyColumn = "travel_id")
    void insertTravel(Travel travel);

    @Update("update other_travel set travel_name=#{travelName},travel_detail=#{travelDetail} where travel_id=#{travelId}")
    void updateTravel(Travel travel);

    @Delete("delete from other_travel where travel_id=#{travelId}")
    void deleteTravelByTravelId(int travelId);

    @Select("select * from other_travel where travel_id=#{travelId}")
    @Results( value = {
            @Result(column = "travel_id", property = "travelId"),
            @Result(column = "travel_id", property = "images",
                    javaType = List.class,
                    many = @Many(select = "com.bishe.demo.modules.other.dao.ImageDao.getImageByTravelId")),
            @Result(column = "travel_id", property = "user",
                    javaType = User.class,
                    many = @Many(select = "com.bishe.demo.modules.account.dao.UserDao.getUserByTravelId")),
    })
    Travel getTravelByTravelId(int travelId);

    @Select("select * from other_travel ot left join other_user_travel ou on ot.travel_id=ou.travel_id where ou.user_id=#{userId}")
    @Results(id = "travelResult", value = {
            @Result(column = "travel_id", property = "travelId"),
            @Result(column = "travel_id", property = "images",
                    javaType = List.class,
                    many = @Many(select = "com.bishe.demo.modules.other.dao.ImageDao.getImageByTravelId")),
    })
    List<Travel> getTravelsByUserId(int userId);

    @Select("<script>"
            + "select * from other_travel "
            + "<where> "
            + "<if test='keyword != \"\" and keyword != null'>"
            + " and (travel_name like '%${keyword}%') "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='orderBy != \"\" and orderBy != null'>"
            + " order by ${orderBy} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by travel_id asc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    @ResultMap(value = "travelResult")
    List<Travel> getTravelBySearchBean(SearchBean searchBean);
}
